<template>
  <el-dialog :title="titleName" custom-class="dict-dialog" width="580px"
             :visible.sync="visible"
             center
             :before-close="modelClose"
             @open="modelOpen"
             :close-on-click-modal="false">
    <el-form :rules="rules"
              ref="dictHandleForm"
              :model="modelData"
              :disabled="formDisabled"
              v-loading="loading">
      <el-row :span="24" >
        <el-col :span="24">
          <el-form-item label="父节点" :label-width="formLabelWidth" prop="pId" >
            <el-cascader
              :disabled="isDisabled"
              style="width: 100%;"
              :options="options"
              :props="{ checkStrictly: true, children: 'childrens', value: 'id', label: 'name'}"
              clearable
              :value="modelData.pId"
              @change="handleChange"></el-cascader>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :span="24" >
        <el-col :span="24">
          <el-form-item label="字典编码" :label-width="formLabelWidth" prop="code" >
            <el-input v-model.trim="modelData.code" maxlength="32" autocomplete="off" placeholder="请输入字典编码(用于快速查询)"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :span="24" >
        <el-col :span="24">
          <el-form-item label="字典名称" :label-width="formLabelWidth" prop="name" >
            <el-input v-model.trim="modelData.name" maxlength="32" autocomplete="off" placeholder="请输入可描述字典含义的名称,如中文描述"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :span="24" >
        <el-col :span="24">
          <el-form-item label="程序名称" :label-width="formLabelWidth" prop="appName" >
            <el-input v-model.trim="modelData.appName" maxlength="32" autocomplete="off" placeholder="请输入英文名称(用于程序查询)"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :span="24" >
        <el-col :span="24">
          <el-form-item label="启用状态" :label-width="formLabelWidth" prop="enable">
            <el-select v-model="modelData.enable" placeholder="选择是否启用" style="width: 450px">
              <el-option v-for="item of $enums.OTHERS" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" v-if="btnVisible">
      <el-button type="primary" @click="formSubmit" :loading="loading">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'menuMgrHandleDialog',
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    modelType: {
      type: String,
      required: true,
      default: () => {
        return 'info';
      },
    },
    modelData: {
      type: Object,
      default: () => {
        return {
          app: process.env.VUE_APP_SYSTEM_NAME,
          id: 1,
          code: '',
          name: '',
          appName: '',
          enable: 1
        };
      },
    },
  },
  data() {
      return {
        titleName: '详情',
        formLabelWidth: '80px',
        dialogFormVisible: false,
        formDisabled: false,
        isDisabled: false,
        btnVisible: true,
        loading: false,
        rules: {
          app: this.$Validate.otherTxt(true, '请输入所属应用'),
          code: this.$Validate.idNumber(true, '请输入字典编码'),
          name: this.$Validate.otherTxt(true, '请输入字典名称'),
          appName: this.$Validate.otherTxt(true, '请输入字典程序名称'),
        },
        options: []
      };
  },
  methods: {
    // 解决el-input莫名无法输入的问题
    change() {
      this.$forceUpdate();
    },
    // 对话框打开
    modelOpen() {
      this.options = this.$dictList.filter(item => item.level===1 );
      this.removeEmptyChildren(this.options);
      switch (this.modelType) {
        case 'add':
          this.isDisabled = this.modelData.pId ? true : false;
          this.modelTypeChange('添加字典', false, true);
          break;
        case 'info':
          this.modelTypeChange('字典详情', true, false);
          break;
        case 'edit':
          this.isDisabled = true;
          this.modelTypeChange('编辑字典', false, true);
          break;
        default:
          break;
      }
    },
    // 模式切换
    modelTypeChange(titleName, formDisabled, btnVisible) {
      this.titleName = titleName;
      this.formDisabled = formDisabled;
      this.btnVisible = btnVisible;
    },
    // 提交表单
    formSubmit() {
      // 参数校验
      this.$refs.dictHandleForm.validate((valid) => {
        if (valid) {
          switch (this.modelType) {
            // 添加字典
            case 'add':
              this.handleAdd(this.modelData);
              break;
            // 编辑字典
            case 'edit':
              this.handleEdit({
                id: this.modelData.id,
                code: this.modelData.code,
                name: this.modelData.name,
                appName: this.modelData.appName,
                enable: this.modelData.enable
              });
              break;
            default:
              break;
          }
        }
      });
    },
    handleChange(data){
      this.modelData.pId = data && data[0] ? data[data.length - 1] : null;
    },
    // 新增
    handleAdd(formData) {
      this.loading = true;
      this.$api.dictInfo
        .add(formData)
        .then((res) => {
          this.$message.success('添加字典成功');
          this.loading = false;
          this.modelClose();
          this.$emit('loadList');
          this.$store.dispatch("ddAdmin/dict/loadDict", false, {root: true});
        })
        .catch((err) => {
          console.log(err);
          this.loading = false;
        });
    },
    // 编辑
    handleEdit(formData) {
      // 更新字典
      this.loading = true;
      this.$api.dictInfo
        .update(formData)
        .then((res) => {
          this.$message.success('更新字典成功');
          this.loading = false;
          this.modelClose();
          this.$emit('loadList');
          this.$store.dispatch("ddAdmin/dict/loadDict", false, {root: true});
        })
        .catch((err) => {
          this.loading = false;
        });
    },
    // 重置表单
    resetForm() {
      this.$nextTick(() => {
        this.$refs.dictHandleForm.resetFields();
      });
    },
    // 对话框关闭
    modelClose() {
      // 重置表单
      this.resetForm();
      // 直接修改父组件的属性
      this.$emit('update:visible', false);
    },
    removeEmptyChildren (node) {
      node.forEach(item =>{
        if('childrens' in item && item.childrens.length === 0){
          delete item.childrens
        }else if ('childrens' in item && item.childrens.length){
          this.removeEmptyChildren(item.childrens)
        }
      })
    },
  },
}
</script>

<style lang="scss" scope>
.menu-dialog {
  .el-dialog__body {
    max-height: 50vh;
  }
  .custom-height {
    .el-input__inner {
      height: 32px !important;
    }
  }
}
</style>
